# coding=utf-8
import os, time, random, base64
from wcs.commons.config import Config
from wcs.services.client import Client
from werkzeug.utils import secure_filename

config_file = os.path.join(os.path.expanduser("~"), ".wcscfg")
cfg = Config(config_file)  # 加载配置文件
cli = Client(cfg)  # 初始化Client
bucket = 'wine'  # 上传图片的空间名
baseUrl = "http://img.geda.me/"  # 图片访问域名
AK = "05d6e539c06dcdd620ab71e97ea2201592d9521b"
SK = "ca46bf2f3aad2da759eea2c6aecd1d80832d7202"
import sys


# 上传文件
def upload_book(book_path, cdn_path):
    try:
        c = cli.simple_upload(book_path, bucket, cdn_path)  # 参数分别为：本地路径，空间名，CDN路径
        if c[0] == 200 or c[0] == 406:  # 406为该路径已经有文件了
            os.remove(book_path)
            status = 'success'
        else:
            status = "error"
    except Exception as e:
        print e
        status = 'file error'
    data = {
        "url": cdn_path,
        "status": status
    }
    return data


# 删除文件
def delete_img(key):
    flag = True
    try:
        res = cli.delete(bucket, key)
        print res
    except Exception as e:
        print e
        flag = False
    return flag


# 上传商品封面
def goods_cover(file_base, img_format, sj, img_type):
    try:
        if img_format == 'png':
            re_str = 'data:image/png;base64,'
        elif img_format == 'gif':
            re_str = 'data:image/gif;base64,'
        else:
            re_str = 'data:image/jpeg;base64,'
        bstr = file_base.replace(re_str, '')
        con = base64.b64decode(bstr)
        user_path = os.path.expanduser('~')
        save_dir = os.path.join(user_path, 'temp')
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        img_name = str(int(time.time()*1000)) + '.' + img_format
        local_path = save_dir + '/' + img_name
        with open(local_path, 'wb') as f:
            f.write(con)
        cdn_path = 'wine/' + img_type + '/' + str(sj) + '/' + img_name
        res = upload_book(local_path, cdn_path)
        if res['status'] == 'success':
            return cdn_path
        else:
            return ''
    except Exception as e:
        print e
        return ''


# 上传课程文件
def course_img(file_img, tid, img, cid):
    if file_img:
        img_name = file_img.filename
        user_path = os.path.expanduser('~')
        save_dir = os.path.join(user_path, 'temp')
        img_list = img_name.split('.')
        apk_str = img_list[len(img_list) - 1]
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        file_img.save(os.path.join(save_dir, img_name))
        local_path = save_dir + '/' + img_name
        cdn_path = 'girl/' + str(img) + '/' + str(tid) + '/' + str(cid) + '/' + str(int(time.time())) + \
                   str(random.randint(10, 99)) + '.' + str(apk_str)
        res = upload_book(local_path, cdn_path)
        if res['status'] == 'success':
            return res['url']
        else:
            return ''
    else:
        return ''


# 上传教师头像
def upload_teacher_top(uid, top_file):
    img_name = top_file.filename
    if img_name:
        user_path = os.path.expanduser('~')
        save_dir = os.path.join(user_path, 'temp')
        img_list = img_name.split('.')
        apk_str = img_list[len(img_list) - 1]
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        top_file.save(os.path.join(save_dir, img_name))
        local_path = save_dir + '/' + img_name
        cdn_path = 'header/' + str(uid) + str(int(time.time()*1000)) + '.' + str(apk_str)
        res = upload_book(local_path, cdn_path)
        if res['status'] == 'success':
            return res['url']
        else:
            return ''
    else:
        return ''


# 上传课程文件
def ajax_goods_img(file_img, gid, types):
    if file_img:
        img_name = file_img.filename
        user_path = os.path.expanduser('~')
        save_dir = os.path.join(user_path, 'temp')
        img_list = img_name.split('.')
        apk_str = img_list[len(img_list) - 1]
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        file_img.save(os.path.join(save_dir, img_name))
        local_path = save_dir + '/' + img_name
        cdn_path = 'wine/' + str(types) + '/' + str(gid) + '/' + str(int(time.time())) + \
                   str(random.randint(10, 99)) + '.' + str(apk_str)
        res = upload_book(local_path, cdn_path)
        if res['status'] == 'success':
            return res['url']
        else:
            return ''
    else:
        return ''


def upload_image(upFile, cdn_path, oldname):
    pcsystem = sys.platform
    # 保存至本地
    if pcsystem.startswith('win'):
        base = 'c:/tmp_upload/'
        if not os.path.exists(base):
            os.makedirs(base)
        upFile.save(os.path.join(base, oldname))
        localPath = base + oldname
    else:
        base = '/tmp_upload/'
        if not os.path.exists(base):
            os.makedirs(base)
        upFile.save(os.path.join(base, oldname))
        localPath = base + oldname
    c = cli.simple_upload(localPath, bucket, cdn_path)  # 参数分别为：本地路径，空间名，CDN路径
    if c[0] == 200 or c[0] == 406:  # 406为该路径已经有文件了
        os.remove(localPath)
        status = 'success'
    else:
        status = "error"
    data = {
        "url": cdn_path,
        "status": status
    }
    return data
